package org.sean.framework.ms.config;

import feign.codec.Decoder;
import feign.optionals.OptionalDecoder;
import org.sean.framework.aspect.SynchronizationAspect;
import org.sean.framework.feign.ClientEntityDecoder;
import org.sean.framework.redis.NumberRedisTemplate;
import org.sean.framework.redis.RedisService;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.ControllerAdvice;

/**
 * 自动配置
 */
@Configuration
public class MSApplicationConfiguration {

    @Configuration
    @ConditionalOnClass(RedisTemplate.class)
    @ConditionalOnBean(NumberRedisTemplate.class)
    static class SynchronizationConfiguration {

        @Bean
        @ConditionalOnBean(RedisService.class)
        public SynchronizationAspect synchronizationAspect(RedisService redisService) {
            return new SynchronizationAspect(redisService);
        }
    }

    /**
     * @see org.springframework.cloud.openfeign.FeignClientsConfiguration
     */
    @Configuration
    @ControllerAdvice
    static class FeignConfiguration {

        @Bean
        @Primary
        @ConditionalOnClass(Decoder.class)
        public Decoder feignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
            return new OptionalDecoder(
                    new ClientEntityDecoder(new SpringDecoder(messageConverters)));
        }

    }

}
